{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-0",
   "metadata": {},
   "source": [
    "# Claude + Strata Integration\n",
    "\n",
    "This tutorial demonstrates how to build AI agents using Anthropic's Claude with Klavis Strata MCP servers for enhanced functionality."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-1",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "Before we begin, you'll need:\n",
    "\n",
    "- **Anthropic API key** - Get at [console.anthropic.com](https://console.anthropic.com/)\n",
    "- **Klavis API key** - Get at [klavis.ai](https://klavis.ai/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install the required packages\n",
    "%pip install -q klavis python-dotenv anthropic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import webbrowser\n",
    "from klavis import Klavis\n",
    "from klavis.types import McpServerName, ToolFormat\n",
    "from anthropic import Anthropic\n",
    "\n",
    "# Set environment variables\n",
    "os.environ[\"ANTHROPIC_API_KEY\"] = \"YOUR_ANTHROPIC_API_KEY\"  # Replace with your actual Anthropic API key\n",
    "os.environ[\"KLAVIS_API_KEY\"] = \"YOUR_KLAVIS_API_KEY\"  # Replace with your actual Klavis API key"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-4",
   "metadata": {},
   "source": [
    "## Step 1: Create Strata MCP Server\n",
    "\n",
    "Create a unified MCP server that combines multiple services (Gmail and Slack) for enhanced agent capabilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-5",
   "metadata": {},
   "outputs": [],
   "source": [
    "klavis_client = Klavis(api_key=os.getenv(\"KLAVIS_API_KEY\"))\n",
    "\n",
    "# Create a Strata MCP server with Gmail and Slack integrations\n",
    "response = klavis_client.mcp_server.create_strata_server(\n",
    "    user_id=\"1234\",\n",
    "    servers=[McpServerName.GMAIL, McpServerName.SLACK],\n",
    ")\n",
    "\n",
    "print(f\"🚀 Strata MCP server created successfully!\")\n",
    "\n",
    "# Handle OAuth authorization if needed\n",
    "if response.oauth_urls:\n",
    "    for server_name, oauth_url in response.oauth_urls.items():\n",
    "        webbrowser.open(oauth_url)\n",
    "        print(f\"🔐 Opening OAuth authorization for {server_name}\")\n",
    "        input(f\"Press Enter after completing {server_name} OAuth authorization...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-6",
   "metadata": {},
   "source": [
    "## Step 2: Setup Claude with MCP Tools\n",
    "\n",
    "Set up Claude to use tools from the Strata MCP server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Claude client\n",
    "claude_client = Anthropic(api_key=os.getenv(\"ANTHROPIC_API_KEY\"))\n",
    "\n",
    "# Get MCP server tools in Anthropic format\n",
    "mcp_server_tools = klavis_client.mcp_server.list_tools(\n",
    "    server_url=response.strata_server_url,\n",
    "    format=ToolFormat.ANTHROPIC\n",
    ")\n",
    "\n",
    "print(f\"🤖 Claude configured with {len(mcp_server_tools.tools)} MCP tools!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-8",
   "metadata": {},
   "source": [
    "## Step 3: Create Agent Loop\n",
    "\n",
    "Implement an agentic loop that allows Claude to use MCP tools to complete tasks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define user query\n",
    "user_query = \"Check my latest 5 emails and summarize them in a Slack message to #general channel\"\n",
    "\n",
    "messages = [\n",
    "    {\"role\": \"user\", \"content\": user_query}\n",
    "]\n",
    "\n",
    "# Agent loop to handle tool calls\n",
    "max_iterations = 10\n",
    "iteration = 0\n",
    "\n",
    "while iteration < max_iterations:\n",
    "    iteration += 1\n",
    "    \n",
    "    claude_response = claude_client.messages.create(\n",
    "        model=\"claude-sonnet-4-5-20250929\",\n",
    "        max_tokens=4000,\n",
    "        system=\"You are a helpful assistant. Use the available tools to answer the user's question.\",\n",
    "        messages=messages,\n",
    "        tools=mcp_server_tools.tools\n",
    "    )\n",
    "    \n",
    "    messages.append({\"role\": \"assistant\", \"content\": claude_response.content})\n",
    "    \n",
    "    if claude_response.stop_reason == \"tool_use\":\n",
    "        tool_results = []\n",
    "        \n",
    "        for content_block in claude_response.content:\n",
    "            if content_block.type == \"tool_use\":\n",
    "                function_name = content_block.name\n",
    "                function_args = content_block.input\n",
    "                \n",
    "                print(f\"🔧 Calling: {function_name}, with args: {function_args}\")\n",
    "                \n",
    "                result = klavis_client.mcp_server.call_tools(\n",
    "                    server_url=response.strata_server_url,\n",
    "                    tool_name=function_name,\n",
    "                    tool_args=function_args\n",
    "                )\n",
    "                \n",
    "                tool_results.append({\n",
    "                    \"type\": \"tool_result\",\n",
    "                    \"tool_use_id\": content_block.id,\n",
    "                    \"content\": str(result)\n",
    "                })\n",
    "        \n",
    "        messages.append({\"role\": \"user\", \"content\": tool_results})\n",
    "        continue\n",
    "    else:\n",
    "        final_response = claude_response.content[0].text\n",
    "        print(\"\\n✅ Final Response:\")\n",
    "        print(final_response)\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-10",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "🎉 Congratulations! You've successfully created a Claude agent that can:\n",
    "\n",
    "1. **Read emails** using the Gmail MCP server\n",
    "2. **Send Slack messages** using the Slack MCP server\n",
    "3. **Coordinate multiple services** through Klavis Strata MCP integration\n",
    "\n",
    "This demonstrates the power of combining Claude's advanced reasoning capabilities with Klavis MCP servers for building sophisticated AI workflows that can interact with multiple external services seamlessly."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
